﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public delegate void delegateRun<T>(string server, T t);
    public class SignalRClientHelper<T>
    {
        private HubConnection _conn = null;
        private IHubProxy _proxy = null;
        public event delegateRun<T> eventRun;
        public SignalRClientHelper(string signalrServer, string hubName)
        {
            _conn = new HubConnection(signalrServer, true);
            _proxy = _conn.CreateHubProxy(hubName);
        }

        public void Start(params string[] methods)
        {
            foreach (var method in methods)
            {
                _proxy.On<T>(method, (t) =>
                {
                    eventRun?.Invoke(_conn.Url, t);
                });
            }

            _conn.Start().ContinueWith(task =>
            {
                if (!task.IsFaulted)
                {
                    LogHelper.Info($"与SignalR Server:{_conn.Url}连接成功!");
                }
                else
                {
                    LogHelper.Info($"与SignalR Server:{_conn.Url}连接失败，请确认服务器是否开启!");
                }
            }).Wait();

            _conn.StateChanged += new Action<StateChange>(tak =>
            {
                if (tak.NewState == ConnectionState.Reconnecting)
                {
                    LogHelper.Info($"与SignalR Server:{_conn.Url}尝试重新连接!");
                }
                else if (tak.NewState == ConnectionState.Disconnected)
                {
                    LogHelper.Info($"与SignalR Server:{_conn.Url}连接失败，请确认服务器是否开启!");
                }
            });
            _conn.Closed += () => LogHelper.Info($"与SignalR Server:{_conn.Url}连接已关闭，请确认服务器是否开启!");
        }

    }
}
